package com.wxtwxt.ruralmall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.wxtwxt.ruralmall.auth.feign.MemberFeign;
import com.wxtwxt.ruralmall.auth.feign.ThirdPartyFeign;
import com.wxtwxt.ruralmall.auth.vo.UserLoginVo;
import com.wxtwxt.ruralmall.auth.vo.UserRegisterVo;
import com.wxtwxt.ruralmall.common.constant.AuthServerConstant;
import com.wxtwxt.ruralmall.common.utils.BizCodeEnum;
import com.wxtwxt.ruralmall.common.utils.R;
import com.wxtwxt.ruralmall.common.vo.MemberVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author Wxt
 * @create 2023-04-19 19:53
 */
@Controller
public class LoginController {
    @Resource
    private ThirdPartyFeign thirdPartyFeign;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private MemberFeign memberFeign;

    @ResponseBody
    @GetMapping("/sms/sendCode")
    public R sendCode(@RequestParam("email") String email) {
        String redisCode = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + email);
        if(StringUtils.isNotEmpty(redisCode)) {
            long currentTime = Long.parseLong(redisCode.split("_")[1]);
            if(System.currentTimeMillis() - currentTime < 60 * 1000) {
                return R.error(BizCodeEnum.SMS_CODE_EXCEPTION.getCode(), BizCodeEnum.SMS_CODE_EXCEPTION.getMessage());
            }
        }
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            builder.append(new Random().nextInt(10));
        }
        builder.append("_").append(System.currentTimeMillis());
        String code = builder.toString();
        stringRedisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX + email, code, 1, TimeUnit.MINUTES);
        return thirdPartyFeign.sendCode(email, code.substring(0, 6));
    }

    @PostMapping("/register")
    public String register(@Valid UserRegisterVo userRegisterVo, BindingResult bindingResult, RedirectAttributes redirectAttributes) {
        if(bindingResult.hasErrors()) {
            Map<String, String> errors = bindingResult.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/register.html";
        }
        String code = userRegisterVo.getCode();
        String redisCode = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + userRegisterVo.getEmail());
        if(StringUtils.isNotEmpty(redisCode)) {
            if(code.equals(redisCode.split("_")[0])) {
                stringRedisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + userRegisterVo.getEmail());
                R r = memberFeign.register(userRegisterVo);
                if(r.getCode() == 0) {
                    return "redirect:http://auth.gulimall.com/login.html";
                }else {
                    Map<String, String> errors = new HashMap<>();
                    errors.put("msg", (String) r.get("msg"));
                    redirectAttributes.addFlashAttribute("errors", errors);
                    return "redirect:http://auth.gulimall.com/register.html";
                }
            }else {
                Map<String, String> errors = new HashMap<>();
                errors.put("code", "验证码不正确");
                redirectAttributes.addFlashAttribute("errors", errors);
                return "redirect:http://auth.gulimall.com/register.html";
            }
        }else {
            Map<String, String> errors = new HashMap<>();
            errors.put("code", "验证码不正确");
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/register.html";
        }
    }

    @GetMapping("/login.html")
    public String loginPage(HttpSession session) {
        Object attribute = session.getAttribute(AuthServerConstant.LOGIN_USER);
        if(attribute != null) {
            return "redirect:http://gulimall.com";
        }
        return "login";
    }

    @PostMapping("/login")
    public String login(UserLoginVo userLoginVo, RedirectAttributes redirectAttributes, HttpSession session) {
        R r = memberFeign.login(userLoginVo);
        if(r.getCode() == 0) {
            MemberVo member = r.getData("member", new TypeReference<MemberVo>() {});
            session.setAttribute(AuthServerConstant.LOGIN_USER, member);
            return "redirect:http://gulimall.com";
        }
        Map<String, String> errors = new HashMap<>();
        errors.put("msg", (String) r.get("msg"));
        redirectAttributes.addFlashAttribute("errors", errors);
        return "redirect:http://auth.gulimall.com/login.html";
    }
}
